package com.yneusoft.manage.service;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.common.tool.JwtTool;
import com.yneusoft.dao.entity.User;
import com.yneusoft.dao.mapper.UserMapper;
import com.yneusoft.manage.model.result.GetCurrentUserInfoResult;
import com.yneusoft.manage.model.result.GetImageCodeResult;
import com.yneusoft.manage.model.param.UserLoginParam;
import com.yneusoft.manage.model.result.UserLoginResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;

import java.util.Objects;

import com.yneusoft.common.enums.ResultEnum;


/**
 * @author lt
 * @date 2021/10/20 19:05
 * @description: 登录模块功能实现
 */
@Service
public class LoginManageService {
    @Autowired
    private UserMapper userMapper;

    TimedCache<String, String> timedCache = CacheUtil.newTimedCache(60000);
    LineCaptcha lineCaptcha;

    /**
     * 1、获取图片验证码
     * @return 验证码密钥、base64Data
     */
    public ResponseWrapper getImageCode() {
        RandomGenerator generator = new RandomGenerator("0123456789ABCDEFGHIJKLMNPQRSTUVWXY", 4);
        lineCaptcha = CaptchaUtil.createLineCaptcha(80, 24,4,20);
        lineCaptcha.setGenerator(generator);
        lineCaptcha.createCode();
        String uuid = IdUtil.randomUUID();
        timedCache.put("imageCodeKey",uuid);
        GetImageCodeResult imageCodeResult = new GetImageCodeResult();
        imageCodeResult.setImageCodeKey(uuid);
        imageCodeResult.setImageCodeBase64(lineCaptcha.getImageBase64Data());
        return ResponseWrapper.markSuccess(imageCodeResult);
    }

    /**
     * 2、用户登录
     * @param param 用户登录请求参数
     * @return token、name
     */
    public ResponseWrapper login(UserLoginParam param) {
        String key = timedCache.get("imageCodeKey");
        //验证码是否过期
        if(key == null){
            return ResponseWrapper.markError(ResultEnum.CAPTCHA_TIMEOUT);
        }
        else{
            //验证码密钥是否错误
            if(!key.equals(param.getImageCodeKey())){
                return ResponseWrapper.markError(ResultEnum.CAPTCHA_TIMEOUT);
            }
            else{
                //校验验证码是否错误
                if (!lineCaptcha.verify(param.getImageCode())) {
                    return ResponseWrapper.markError(ResultEnum.CAPTCHA_CHECK_ERROR);
                } else {
                    LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
                    String phone = param.getPhone();
                    String password = param.getPassword();
                    wrapper.eq(StringUtils.isNotBlank(phone),User::getPhone,phone)
                            .eq(StringUtils.isNotBlank(password),User::getPassword,password)
                            .ne(User::getStateId,0);
                    User userDB =userMapper.selectOne(wrapper);
                    //校验用户是否符合登录条件（手机号、密码正确，状态为启用）
                    if(userDB == null){
                        return ResponseWrapper.markError(ResultEnum.LOGIN_ERROR);
                    }
                    else{
                        UserLoginResult userLoginResult = new UserLoginResult();
                        userLoginResult.setToken(JwtTool.getToken(userDB.getAid()));
                        userLoginResult.setName(userDB.getName());
                        return ResponseWrapper.markSuccess(userLoginResult);
                    }

                }

            }
        }


    }

    /**
     * 3、根据token获取当前用户信息
     * @return name
     */
    public ResponseWrapper getCurrentUserInfo(){
        HttpServletRequest request= ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = request.getHeader("token");
        DecodedJWT jwt = JwtTool.getToken(token);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAid,jwt.getClaim("aid").asInt())
                .ne(User::getStateId,0);
        User userDB = userMapper.selectOne(wrapper);
        if (userDB != null) {
            GetCurrentUserInfoResult getCurrentUserInfoResult = new GetCurrentUserInfoResult();
            getCurrentUserInfoResult.setName(userDB.getName());
            return ResponseWrapper.markSuccess(getCurrentUserInfoResult);
        }
        else {
            return ResponseWrapper.markError(ResultEnum.USER_NOT_EXISTS);
        }
    }

}
